import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:xvideos/hj_model/comment/comment_model.dart';
import 'package:xvideos/hj_model/comment/reply_model.dart';
import 'package:xvideos/hj_page/comment/comment_input_view.dart';
import 'package:xvideos/hj_utils/api_service/comment_service.dart';
import 'package:xvideos/hj_utils/date_time_util.dart';
import 'package:xvideos/hj_utils/global.dart';
import 'package:xvideos/tools_base/debug_log.dart';

import '../../hj_model/comment/comment_list_res.dart';
import '../../tools_base/file_upload/file_upload_tool.dart';
import '../../tools_base/file_upload/image_upload_result_model.dart';

const commentInputId = 'detail_comment_input_id';

mixin CommentMixin on GetxController {
  final comments = <CommentModel>[];

  final commentFocus = FocusNode();
  final commentController = TextEditingController();

  Function(int)? totalCallback;

  CommentModel? replyComment;

  ReplyModel? replyCommentModel;
  int page = 1;
  String? hintText;
  Rx<String?> selectedImagePath = Rx<String?>(null);
  RefreshController? refreshController;
  final quickSearchList = <CommentLink>[];
  String? id;
  String? objType;

  RxBool isSendingMsg = false.obs;
  Rx<int> totalCtCount = 0.obs;
  sendCommentOrReplay() async {
    String content = commentController.text;
    if (content.isEmpty) {
      showToast('请输入评论内容哦～');
      return;
    }
    isSendingMsg.value = true;
    String? sendImagePath;
    if (selectedImagePath.value?.isNotEmpty == true) {
      try {
        ImageUploadResultModel? imgResult = await FileUpLoadTool().uploadImage(selectedImagePath.value!);
        sendImagePath = imgResult?.coverImg ?? "";
        if (sendImagePath.isEmpty) {
          isSendingMsg.value = false;
          showToast("图片上传失败!");
          return;
        }
      } catch (e) {
        debugLog(e);
        isSendingMsg.value = false;
        showToast("图片上传失败!");
        return;
      }
    }

    try {
      if (replyComment != null) {
        // 回复评论
        final res = await CommentService.sendReply(
          id,
          2,
          content,
          rid: replyCommentModel?.id,
          cid: replyComment?.id,
          toUserID: replyCommentModel?.toUserID,
          objType: objType,
          image: sendImagePath,
        );
        if (res != null) {
          replyComment?.info ??= [];
          replyComment?.info?.insert(0, res);
          replyComment?.commCount = replyComment?.info?.length ?? 0;
          replyComment = null;
          replyCommentModel = null;
          hintText = null;
          showToast('回复成功');
        }
        update();
      } else {
        // 评论
        final res = await CommentService.sendComment(
          id,
          1,
          content,
          objType ?? '',
          image: sendImagePath,
        );
        if (res == null) {
          hintText = null;
        } else {
          //showToast('评论成功，请耐心等待审核');
          showToast('评论成功');
          hintText = null;
          int insertIndex = -1;
          for (int i = 0; i < comments.length; i++) {
            if (!comments[i].isHideLikeOrComment) {
              insertIndex = i;
              break;
            }
          }
          if (insertIndex == -1) {
            insertIndex = comments.length;
          }
          comments.insert(insertIndex, res);
        }
        update();
      }
    } catch (e) {
      debugLog(e);
    }
    selectedImagePath.value = null;
    commentController.text = "";
    isSendingMsg.value = false;
  }

  // isSend: true 点击了发送按钮, 如果没有发送内容弹键盘, 有内容直接发送
  readyReplyComment(CommentModel? comment, {ReplyModel? replyModel, bool? isSend}) async {
    replyComment = comment;
    replyCommentModel = replyModel;
    if (replyModel != null) {
      hintText = '回复：${replyModel.userName ?? ''}';
    }
    if (comment != null && hintText == null) {
      hintText = '回复：${comment.userName ?? ''}';
    }
    if (isSend == true && commentController.text.isNotEmpty) {
      update();
      sendCommentOrReplay();
    } else {
      final result = await Get.bottomSheet(
        CommentInputView(
          hint: hintText,
          textEditController: commentController,
          selectedImgPath: selectedImagePath.value,
          imgCallback: (value) {
            selectedImagePath.value = value;
          },
        ),
        backgroundColor: Colors.transparent,
        barrierColor: Colors.transparent,
        enableDrag: false,
        settings: RouteSettings(name: CommentInputView.routeName),
        useRootNavigator: true,
      );
      if (result == true) {
        update();
        sendCommentOrReplay();
      }
    }
  }

  // 获取评论
  Future fetchComments(String id, {bool isRefresh = false}) async {
    try {
      if (isRefresh) {
        page = 1;
      }
      final currentT = DateTimeUtil.format2utc(DateTime.now()) ?? "";
      final result = await CommentService.getCommentList(id, currentT, page, 20);
      totalCtCount.value = result?.total ?? 0;
      totalCallback?.call(result?.total ?? 0);
      refreshController?.refreshCompleted();
      refreshController?.loadComplete();
      if (!(result?.hasNext ?? false)) {
        refreshController?.loadNoData();
      }
      if (page == 1) {
        comments.clear();
      }
      comments.addAll(result?.list ?? []);
      quickSearchList.addAll(result?.quickSearchList ?? []);
      page += 1;
      for (var e in comments) {
        final commentCount_ = e.commCount ?? 0;
        final replys = e.info ?? [];
        e.haveMoreData = commentCount_ > replys.length;
      }
    } catch (e) {
      refreshController?.refreshCompleted();
      refreshController?.loadComplete();
      debugLog(e);
    }
    update();
  }
}
